package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class Utils {

    public static String deserializeString(File file) {
	int len;
	char[] chr = new char[4096];
	final StringBuffer buffer = new StringBuffer();
	FileReader reader = null;
	try {
	    reader = new FileReader(file);
	    while ((len = reader.read(chr)) > 0) {
		buffer.append(chr, 0, len);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		reader.close();
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
	return buffer.toString();
    }

    public static byte[] getBytesFromFile(File file) {
	if (!file.exists()) {
	    return new byte[0];
	}
	try {
	    // get the size of the file
	    long length = file.length();
	    if (length > Integer.MAX_VALUE) {
		throw new RuntimeException(String.format(
			"The file %s is too large to be hold in a byte array",
			file.getName()));
	    }

	    int len = (int) length;
	    byte[] bytes = new byte[len];

	    InputStream in = new FileInputStream(file);

	    // read in the bytes
	    int offset = 0, n = 0;
	    while (offset < len && n >= 0) {
		n = in.read(bytes, offset, len - offset);
		offset += n;
	    }

	    if (offset < len) {
		throw new RuntimeException(
			"Faile to read all contents of file: " + file.getName());
	    }

	    in.close();
	    return bytes;
	} catch (IOException e) {
	    throw new RuntimeException(e);
	}
    }
}
